<template>
	<view class="container">
		<view class="inner" :style="{ backgroundImage: vdata.activityDetail.activityTemplateNo === 'ACTE006' && 'url(https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/fcca73b3-5a89-4309-a950-21ff54b4611b.png)' }">
			<!-- <view class="activity-name">
				邮惠云团
			</view> -->
			<view class="activity-times">
				{{ vdata.numEveryoneText }}
			</view>
			<view class="activity-time">
				限时活动：{{ dayjs(vdata.activityDetail.startTime).format('M[月]D[日]') }} ~ {{ dayjs(vdata.activityDetail.endTime).format('M[月]D[日]') }}
			</view>
			<!-- <view class="activity-coupon">
				<text>￥</text>
				<text>{{ vdata.couponPriceTotal }}</text>
			</view> -->
			<view v-if="vdata.activityDetail.activityTemplateNo === 'ACTE006'" class="sq-state" @click="goToCoupon">已授权，去领券</view>
			<view v-else class="sq-state" @click="exitProgram">{{ vdata.btnConfig.text }}</view>
		</view>
	</view>
	<!-- 授权登录弹窗 -->
	<gzLoginPopup ref="gzLoginPopupRef" v-model:isLogin="vdata.isLogin" @isLoginCallback="isLoginCallback"></gzLoginPopup>
</template>

<script setup>
	import { ref, reactive, getCurrentInstance } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import storageManage from '@/util/storageManage.js'
	import { $getAwardList, $couponDetail, $getCouponAward, $getFansAwardActivity } from '@/http/apiManager.js';
	import dayjs from 'dayjs'
	
	const { $infoBox } = getCurrentInstance().appContext.config.globalProperties

	const gzLoginPopupRef = ref()

	const userId = storageManage.userId()
	const fansId = storageManage.fansId()

	const vdata = reactive({
		isLogin: false,	// 用户是否登录
		btnConfig: {	// 按钮配置
			isExit: 0,	// 点击是否退出小程序 默认不 只有存在未使用卡券的情况下 才为1 退出 2 导航到商家列表
			text: '导航到商家列表',	// 按钮文案
		},
		numEveryoneText: '',	// 每人可领取次数文案 只有通过扫码进入小程序 才会有该文案
		scene: null,	// 扫码领券 携带参数
		activityDetail: {}, // 活动详情
		// couponPriceTotal: 0,	// 卡券总额
	})

	// 根据传递过来的卡券状态 优先展示该状态的卡券列表
	onLoad(async ({ activityId, activityDetail, scene }) => {
		vdata.isLogin = storageManage.isLogin()
		vdata.activityDetail = JSON.parse(decodeURIComponent(activityDetail))
		// 标题更改为活动名称
		uni.setNavigationBarTitle({
			title: vdata.activityDetail.activityName || '神券大派发'
		})
		vdata.scene = scene
		// 判断用户是否登录过
		if (!vdata.isLogin) {
			uni.showModal({
				title: '提示',
				content: '请先进行登录注册，再进行参与！',
				success({ cancel }) {
					if (cancel) {
						$infoBox.toast('参与失败')
						vdata.btnConfig.text = '登录失败，无法正常参与活动'
					} else {
						gzLoginPopupRef.value.open() // 打开授权弹框
					}
				}
			})
			return
		}
		// 扫码派券
		if(vdata.activityDetail.activityTemplateNo === 'ACTE006'){
			return
		}
		
		// 扫码领券
		if (scene) {
			scanQrcodeCoupon(scene)
		}else{	// 非扫码进入 查询用户是否有活动奖品
			noScanQrcodeCoupon(storageManage.userId(),activityId,vdata.activityDetail.isCommSubject)
		}
	})
	/**
	 * 扫码派券
	 */
	const goToCoupon = () => {
		// 直接跳转 我的页面并展开会员码
		uni.reLaunch({
			url: `/pages/user/user?open=${1}`
		})
	}
	/**
	 * 扫码领券
	 */
	async function scanQrcodeCoupon(scene) {
		const { activityId, id } = JSON.parse(scene)
		uni.showLoading({ title: '领取中...' })
		try{
			// 拉取领取次数
			const [ result1, /* result2, */ result3 ] = await Promise.allSettled([
				$couponDetail({ qrcodeRecordId: id }),
				// $getAwardList({ activityId }),
				$getCouponAward({ id }),	// 领券
			])
			// 处理领取次数
			const { type, numEveryone } = result1.value.bizData
			if(type == 1){
				vdata.numEveryoneText = `每人仅限领取${numEveryone}次`
			}
			// 处理卡券总金额 result2
			// 处理奖品列表
			// calculateCouponPrice(result2.value.bizData)
			
			// 领取成功
			if(result3.status === 'fulfilled'){
				vdata.btnConfig.text = '立即使用'
				vdata.btnConfig.isExit = 1
				uni.hideLoading()
				uni.showModal({
					title: '提示',
					content: '领取成功',
					success({ cancel }) {
						if (cancel) return;
						uni.navigateTo({
							url: `/pageUser/myCoupon/index?tabCurrent=1&couponState=0`
						})
					}
				})
			}else{	// 抛出异常
				vdata.btnConfig.text = result3.reason
			}
		}catch(e){
			//TODO handle the exception
			
		}
	}
	/**
	 * 登录回调
	 */
	function isLoginCallback(){
		if(!vdata.isLogin){
			$infoBox.toast('登录失败，无法正常参与活动')
			vdata.btnConfig.text = '登录失败，无法正常参与活动'
		}else{
			if(vdata.scene){
				scanQrcodeCoupon(vdata.scene)
			}else{
				$infoBox.toast('领券参数异常，请重新扫码')
				vdata.btnConfig.text = '领券参数异常，请重新扫码'
			}
		}
	}
	
	/**
	 * 非扫码领券
	 */
	const noScanQrcodeCoupon = async (userId,activityId,isCommSubject) => {
		try{
			const [ result1, result2 ] = await Promise.all([
				$getFansAwardActivity({ activityId }),	// 用户账户下是否存在当前活动奖品
				$getAwardList({ activityId })	// 获取当前活动配置的奖品列表
			])
			// 处理按钮显示文案 result1
			if(result1.bizData == 1){	// 存在未使用奖品
				vdata.btnConfig.text = '立即使用'
				vdata.btnConfig.isExit = 1
			}else{	// 不存在奖品
				if(isCommSubject === 0){	// 同主体
					vdata.btnConfig.text = '已授权，导航到商家列表'
					vdata.btnConfig.isExit = 2
				}else{ // 异主体
					vdata.btnConfig.text = '导航到商家列表'
					vdata.btnConfig.isExit = 2
				}
				vdata.activityDetail.couponId = result2.bizData[0].awardId	// 活动配置奖品ID
			}
			// 处理奖品列表
			// calculateCouponPrice(result2.bizData)
		}catch(e){
			//TODO handle the exception
		}
	}
	/**
	 * 根据奖品列表 计算卡券总额
	 */
	const calculateCouponPrice = (couponList) => {
		let couponPrice = 0
		if (couponList && couponList.length) {
			couponPrice = couponList.reduce((accumulator, currentValue) => accumulator + currentValue.awardPrice, 0) / 100
		}
		vdata.couponPriceTotal = couponPrice
	}
	/**
	 * 退出小程序
	 */
	const exitProgram = () => {
		if(vdata.btnConfig.isExit == 1){
			wx.exitMiniProgram()
		}else if(vdata.btnConfig.isExit == 2){
			// 导航到商家列表
			if(!vdata.activityDetail.couponId){
				$infoBox.toast('当前活动奖品配置有误')
				return
			}
			uni.navigateTo({
				url: `/pageUser/myCoupon/mchList?couponId=${vdata.activityDetail.couponId}`
			})
		}
	}
</script>

<style lang="less" scoped>
	.container {
		width: 100%;
		height: 100vh;
		overflow-y: scroll;
		background-color: #e72118;

		&::-webkit-scrollbar {
			display: none;
		}

		.inner {
			--zzIssue: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/fcca73b3-5a89-4309-a950-21ff54b4611b.png');	// 郑州派券背景
			--zzGet: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/0c5d6b90-8631-4bee-9098-73813321df01.png');	// 郑州领券背景
			--ccIssue: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/f15cf406-496b-44b0-a5f4-16a77ad92932.png');	// 长春派券背景
			--ccGet: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/b74afe2b-e6bd-4b87-b88a-ee524725b358.png');	// 长春领券背景
			position: relative;
			width: 100%;
			overflow: hidden;
			height: 1448rpx;
			box-sizing: border-box;
			// background: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/e3d7a450-dc66-4b91-b666-cc3e2926f5ca.png') no-repeat left top / 100% 100%;
			background: var(--zzGet) no-repeat left top / 100% 100%;	// 郑州 扫码领券背景
			padding-top: 730rpx;
			
			.activity-name{
				padding-top: 50rpx;
				transform: rotateZ(-4deg);
				text-align: center;
				font-family:YouSheBiaoTiHei;
				font-size:150rpx;
				color:rgb(255, 248, 245);
				text-shadow:4px 4px #fa6c3d, 4px 8px rgba(0,0,0,0.5);
			}
			.activity-times{
				font-size: 36rpx;
				text-align: center;
				font-weight: bold;
				min-height: 50rpx;
			}
			.activity-time {
				text-align: center;
				font-size: 28rpx;
				margin-top: 20rpx;
			}
			.activity-coupon{
				width: 100%;
				text-align: center;
				transform: rotateZ(3deg);
				text{
					font-family:YouSheBiaoTiHei;
					color:rgba(255, 40, 30, 0.7);
					text-shadow:1px 1px 4px #fff, 0 0 0 #000;
					&:nth-child(1){
						font-size:70rpx;
						letter-spacing: -15px;
					}
					&:nth-child(2){
						font-size:100rpx;
					}
				}
			}
			
			.sq-state {
				margin: 450rpx auto 0;
				background: linear-gradient(to bottom, #e72118,#ed322b, #f0514b,#ed322b, #e72118);
				box-shadow: inset 4rpx 4rpx 8rpx #f9ab7f,inset -4rpx -6rpx 8rpx #f9ab7f;
				border-radius: 55rpx 55rpx 55rpx 55rpx;
				font-size: 40rpx;
				color: #FFFFFF;
				text-align: center;
				padding: 24rpx 0;
				width: calc(100% - 56rpx);
				text-shadow: 4rpx 8rpx 8rpx rgba(0,0,0,0.9);
			}
		}
	}
</style>